import os.path

class IniParser:
  def __init__(self):
    self._stripChars = ' \t\r\n'

  def parse(self, filename):
    if not os.path.exists(filename):
      raise Exception('Can not find the file %s' % filename)

    fs = open(filename, 'r')

    groups = {}
    while True:
      try:
        line = fs.next()
        line = line.strip(self._stripChars)
        if line.find(';') == 0:
          continue
        
        if line.find('[') == 0:
          name = line.strip('[]').strip(self._stripChars)
          group = self.readGroup(fs)
          if not groups.has_key(name):
            groups[name] = group
      except StopIteration, err:
        break

    return groups

  def readGroup(self, fs):
    group = {}
    while True:
      try:
        line = fs.next()
        line = line.strip(self._stripChars)
        
        if line.find(';') == 0:
            continue
          
        if line == '':
          break
        
        name, value = line.split(':')
        name = name.strip(self._stripChars)
        value = value.strip(self._stripChars)
        
        if not group.has_key(name):
          group[name] = value
      except StopIteration, err:
        break

    return group

#######################################################################
# test code
if __name__ == '__main__':
  import sys
  import getopt
  
  try:
    opts, args = getopt.getopt(sys.argv[1:], "hd:v", ["help", "filename="])
  except getopt.GetoptError, err:
    print 'Get opt failed.%s%s' % (os.linesep, str(err))
    sys.exit(2)

  filename = ''
  for opt, arg in opts:
    if opt.lower() == '--filename' or opt.lower() == '--f':
      filename = os.path.realpath(arg)
      print 'Source File: %s' % filename
      print '------------------------------------'

  if filename == '':
    print 'Please enter a file name by \'--filename=\' or \'--f\' argument.'
    
  if not os.path.exists(filename):
    print 'Can not find the file: %s' % filename
    sys.exit(2)

  parser = IniParser()
  groups = parser.parse(filename)

  for key, group in groups.items():
    print '[%s]' % key
    for key, value in group.items():
      print '%s : %s' % (key, value)
    print ''
